package com.moqianfan.mcuassistant.fragment.play;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.moqianfan.mcuassistant.R;
import com.moqianfan.mcuassistant.activity.WebInfoActivity;
import com.moqianfan.mcuassistant.adapter.CommDataAdapter;
import com.moqianfan.mcuassistant.bean.Article;
import com.moqianfan.mcuassistant.fragment.BaseFragment;
import com.moqianfan.mcuassistant.utils.LogUtil;
import com.squareup.picasso.Picasso;
import com.yalantis.phoenix.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnItemClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by Administrator on 2017/6/16.
 * 移动互联
 */

public class ReadFragment extends BaseFragment {

    @BindView(R.id.list_wx)
    ListView listWx;
    @BindView(R.id.pull_refresh)
    PullToRefreshView pull;

    private List<Article> articles;
    private CommDataAdapter<Article> adapter;
    private boolean isButtom = false;
    private boolean isLoading = false;

    private static String TAG = "ReadFragment";

    @Override
    public View findViews(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_wxnews, container, false);
    }

    @Override
    public void initViews() {
        articles = new ArrayList<>();

        pull.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pull.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        articles.clear();
                        getArticle();
                    }
                }, 1000);
            }
        });



        listWx.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        //滚动到底部
                        if (listWx.getLastVisiblePosition() == (adapter.getCount() - 1)) {
                            LogUtil.w(TAG, "到底部了");
                            isButtom = true;
                        }
                }
                if (isButtom && !isLoading) {
                    getArticle();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    @Override
    public void loadData() {
        getArticle();
    }

    public void getArticle() {
        isLoading = true;
        BmobQuery<Article> query = new BmobQuery<>();
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setSkip(articles.size());
        query.setLimit(20);
        query.order("-time");
        query.findObjects(new FindListener<Article>() {
            @Override
            public void done(List<Article> list, BmobException e) {
                if (null == e) {
                    for (Article item : list) {
                        LogUtil.w(TAG, item.toString());
                        articles.add(item);
                    }
                    handler.sendEmptyMessage(0x123);
                } else {
                    handler.sendEmptyMessage(0x124);
                    LogUtil.w(TAG, e.toString());
                }
                isLoading = false;
            }
        });
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0x123:
                    updateUI();
                    isButtom = false;
                    break;
            }
            pull.setRefreshing(false);
            return true;
        }
    });

    public void updateUI() {
        if (null == adapter) {
            adapter = new CommDataAdapter<Article>(articles, R.layout.view_item_article) {
                @Override
                public void bindView(ViewHolder holder, Article obj) {
                    holder.setText(R.id.txt_item_info, obj.getTime() + " | " + obj.getAuthor());
                    holder.setText(R.id.txt_item_title, obj.getTitle());
                    holder.setText(R.id.txt_item_desc, obj.getDesc());
                    if (!TextUtils.isEmpty(obj.getPicUrl()))
                        Picasso.with(getContext()).load(obj.getPicUrl()).placeholder(R.drawable.default_wx)
                                .resize(100, 100).into((ImageView) holder.getView(R.id.image_item_url));
                }
            };
            listWx.setAdapter(adapter);
        } else {
            adapter.setmData(articles);
        }
        pull.setRefreshing(false);
    }

    @OnItemClick(R.id.list_wx)
    public void OnItemOnClick(AdapterView<?> view, View view1, int i, long l) {
        Intent inten = new Intent(getActivity(), WebInfoActivity.class);
        inten.putExtra("title", articles.get(i).getTitle());
        inten.putExtra("url", articles.get(i).getUrl());
        inten.putExtra("picUrl", articles.get(i).getPicUrl());
        inten.putExtra("desc", articles.get(i).getTime() + " | " + articles.get(i).getAuthor());
        startActivity(inten);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
